import { OnInit, Component, EventEmitter, Output, ViewChild } from '@angular/core';
import { OperationNotification, OperationType } from 'src/app/project/model/common/operation-notification';
import { ComprehensiveScoreDTO } from 'src/app/project/model/icm/icm-student-academic/comprehensive-evaluation/comprehensive-evaluation.dto';
import { NgForm, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { FormUtil } from '@shared/utils/form-util';
import { ComprehensiveScoreService } from '../../../service/icm/icm-student-academic/comprehensive-evaluation/comprehensive-score.service';
import { NzMessageService } from 'ng-zorro-antd';
import { AcademicPointDTO } from '../../../model/icm/icm-student-academic/comprehensive-evaluation/academic-point.dto';
import { IdeologicalPointDTO } from '../../../model/icm/icm-student-academic/comprehensive-evaluation/ideological-point.dto';
import { StylisticPointDTO } from '../../../model/icm/icm-student-academic/comprehensive-evaluation/stylistic-point.dto';
import { SystemFileDTO } from 'src/app/project/model/icm/icm-global/system-file/system-file-dto';
import { AttachSmallComponent } from '../../../../shared/common-component/attach-small.component';

@Component({
  selector: 'app-comprehensive-evaluation-detail',
  templateUrl: './comprehensive-evaluation-detail.component.html',
  styles: [],
})
export class ComprehensiveEvaluationDetailComponent implements OnInit {
  constructor(
    private msg: NzMessageService,
    private comprehensiveScoreService: ComprehensiveScoreService,
    private fb: FormBuilder,
  ) {
    this.validateForm = this.fb.group({
      politicalIdeaPoint: [null, [Validators.required]],
      disciplineIdeaPoint: [null, [Validators.required]],
      collectiveIdeaPoint: [null, [Validators.required]],
      basicCivilizationPoint: [null, [Validators.required]],
      apartmentPerformancePoint: [null, [Validators.required]],
      socialPracticePoint: [null, [Validators.required]],
      rewardPointI: [null, [Validators.required]],
      deductionPointI: [null, [Validators.required]],
      pePoint: [null, [Validators.required]],
      activityPoint: [null, [Validators.required]],
      rewardPointS: [null, [Validators.required]],
      deductionPointS: [null, [Validators.required]],
      academicRecord: [null, [Validators.required]],
      rewardPointA: [null, [Validators.required]],
      deductionPointA: [null, [Validators.required]],
    });
  }

  /**
   * 文件类型
   */
  fileType: string;

  /**
   * 附件数据
   */
  attachFiles: SystemFileDTO[];

  /**
   * 附件
   */
  @ViewChild('attachSmallComponent', { static: false })
  attachSmallComponent: AttachSmallComponent;

  /**
   * 附件是否只读
   */
  isReview: boolean;

  /**
   * 附件组件按钮可见性
   */
  isShow: boolean;

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<ComprehensiveScoreDTO>>();

  /**
   * form组件
   */
  @ViewChild('myForm', { static: false })
  public myForm: NgForm;

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 是否补录材料
   */
  isReport = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 学业分数据
   */
  academicPoint: AcademicPointDTO = {
    id: null,
    academicRecord: null,
    rewardPoint: null,
    deductionPoint: 0,
    academicTotal: null,
    files: [],
    fileIds: [],
  };

  /**
   * 思想分数据
   */
  ideologicalPoint: IdeologicalPointDTO = {
    id: null,
    politicalIdeaPoint: null,
    disciplineIdeaPoint: null,
    collectiveIdeaPoint: null,
    basicCivilizationPoint: null,
    apartmentPerformancePoint: null,
    socialPracticePoint: null,
    rewardPoint: null,
    deductionPoint: 0,
    ideologicalTotal: null,
    files: [],
    fileIds: [],
  };

  /**
   * 文体分数据
   */
  stylisticPoint: StylisticPointDTO = {
    id: null,
    pePoint: null,
    activityPoint: null,
    rewardPoint: null,
    deductionPoint: 0,
    stylisticTotal: null,
    files: [],
    fileIds: [],
  };

  /**
   * 综合测评数据
   */
  comprehensiveScore: ComprehensiveScoreDTO = {
    id: null,
    year: null,
    nextYear: null,
    academicPoint: this.academicPoint,
    ideologicalPoint: this.ideologicalPoint,
    stylisticPoint: this.stylisticPoint,
    compAssessProcessStatus: null,
    comprehensiveScoreTotal: 0,
    showOrder: 0,
    isApproval: null,
    nextStatus: null,
    isReport: false,
  };

  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    FormUtil.resetForm(this.myForm.form);
  }

  /**
   * 修改综合测评信息
   * @param isPreView 是否预览
   * @param item 综合测评信息
   * @param isReport 是否补录材料
   */
  edit(isPreView: boolean, item: ComprehensiveScoreDTO, isReport: boolean) {
    this.isPreView = isPreView;
    this.isReport = isReport;
    this.comprehensiveScore = this.initComprehensiveScore(item);
    this.isVisible = true;
  }

  /**
   * 初始化综合测评
   */
  initComprehensiveScore(item: ComprehensiveScoreDTO): ComprehensiveScoreDTO {
    return {
      id: item ? item.id : null,
      year: item ? item.year : null,
      nextYear: item ? Number.parseInt(item.year, 10) + 1 : null,
      academicPoint: item ? item.academicPoint : this.academicPoint,
      ideologicalPoint: item ? item.ideologicalPoint : this.ideologicalPoint,
      stylisticPoint: item ? item.stylisticPoint : this.stylisticPoint,
      compAssessProcessStatus: item ? item.compAssessProcessStatus : null,
      comprehensiveScoreTotal: item ? item.comprehensiveScoreTotal : null,
      showOrder: item ? item.showOrder : null,
      isApproval: item ? item.isApproval : false,
      nextStatus: item ? item.nextStatus : null,
      isReport: item ? item.isReport : false,
    };
  }

  /**
   * 计算思想分小计
   */
  calculateIdeologicalTotal() {
    this.comprehensiveScore.ideologicalPoint.ideologicalTotal =
      (this.comprehensiveScore.ideologicalPoint.politicalIdeaPoint
        ? this.comprehensiveScore.ideologicalPoint.politicalIdeaPoint
        : 0) +
      (this.comprehensiveScore.ideologicalPoint.disciplineIdeaPoint
        ? this.comprehensiveScore.ideologicalPoint.disciplineIdeaPoint
        : 0) +
      (this.comprehensiveScore.ideologicalPoint.collectiveIdeaPoint
        ? this.comprehensiveScore.ideologicalPoint.collectiveIdeaPoint
        : 0) +
      (this.comprehensiveScore.ideologicalPoint.basicCivilizationPoint
        ? this.comprehensiveScore.ideologicalPoint.basicCivilizationPoint
        : 0) +
      (this.comprehensiveScore.ideologicalPoint.apartmentPerformancePoint
        ? this.comprehensiveScore.ideologicalPoint.apartmentPerformancePoint
        : 0) +
      (this.comprehensiveScore.ideologicalPoint.socialPracticePoint
        ? this.comprehensiveScore.ideologicalPoint.socialPracticePoint
        : 0) +
      (this.comprehensiveScore.ideologicalPoint.rewardPoint
        ? this.comprehensiveScore.ideologicalPoint.rewardPoint
        : 0) -
      (this.comprehensiveScore.ideologicalPoint.deductionPoint
        ? this.comprehensiveScore.ideologicalPoint.deductionPoint
        : 0);
  }
  /**
   * 计算文体分
   */
  calculationStylisticTotal() {
    this.comprehensiveScore.stylisticPoint.stylisticTotal =
      (this.comprehensiveScore.stylisticPoint.pePoint ? this.comprehensiveScore.stylisticPoint.pePoint : 0) +
      (this.comprehensiveScore.stylisticPoint.activityPoint
        ? this.comprehensiveScore.stylisticPoint.activityPoint
        : 0) +
      (this.comprehensiveScore.stylisticPoint.rewardPoint ? this.comprehensiveScore.stylisticPoint.rewardPoint : 0) -
      (this.comprehensiveScore.stylisticPoint.deductionPoint
        ? this.comprehensiveScore.stylisticPoint.deductionPoint
        : 0);
  }
  /**
   * 计算学业分
   */
  calculationAcademicTotal() {
    this.comprehensiveScore.academicPoint.academicTotal =
      (this.comprehensiveScore.academicPoint.academicRecord
        ? this.comprehensiveScore.academicPoint.academicRecord
        : 0) +
      (this.comprehensiveScore.academicPoint.rewardPoint ? this.comprehensiveScore.academicPoint.rewardPoint : 0) -
      (this.comprehensiveScore.academicPoint.deductionPoint ? this.comprehensiveScore.academicPoint.deductionPoint : 0);
  }

  /**
   * 保存前处理数据
   */
  beforeSave() {
    this.comprehensiveScore.comprehensiveScoreTotal =
      this.comprehensiveScore.stylisticPoint.stylisticTotal * 0.1 +
      this.comprehensiveScore.ideologicalPoint.ideologicalTotal * 0.2 +
      this.comprehensiveScore.academicPoint.academicTotal * 0.7;
    this.comprehensiveScore.ideologicalPoint.fileIds = [];
    this.comprehensiveScore.ideologicalPoint.files.forEach(file => {
      this.comprehensiveScore.ideologicalPoint.fileIds.push(file.id);
    });
    this.comprehensiveScore.stylisticPoint.fileIds = [];
    this.comprehensiveScore.stylisticPoint.files.forEach(file => {
      this.comprehensiveScore.stylisticPoint.fileIds.push(file.id);
    });
    this.comprehensiveScore.academicPoint.fileIds = [];
    this.comprehensiveScore.academicPoint.files.forEach(file => {
      this.comprehensiveScore.academicPoint.fileIds.push(file.id);
    });
  }

  /**
   * 保存
   */
  save(isApproval: boolean) {
    this.beforeSave();

    this.loading = true;
    if (isApproval) {
      // 送审，根据当前状态，选择下一审批状态
      this.comprehensiveScore.isApproval = true;
      this.comprehensiveScore.nextStatus =
        this.comprehensiveScore.compAssessProcessStatus === 'SELF_ASSESSMENT'
          ? 'CLASS_ASSESSMENT'
          : this.comprehensiveScore.compAssessProcessStatus === 'CLASS_ASSESSMENT'
          ? 'GRADE_REVIEW'
          : this.comprehensiveScore.compAssessProcessStatus === 'GRADE_REVIEW'
          ? 'DONE_ASSESSMENT'
          : this.comprehensiveScore.compAssessProcessStatus === 'DONE_ASSESSMENT'
          ? 'DONE_CLOSE'
          : 'DONE_CLOSE';
      this.comprehensiveScoreService.complete(this.comprehensiveScore.id, this.comprehensiveScore).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('修改失败，请重试'),
        () => this.afterCallCompleted(),
      );
    } else {
      if (!this.myForm.form.valid && !this.isReport) {
        this.loading = false;
        this.msg.info('请补全必填项(标红星*)！');
        return;
      }
      // 仅修改保存
      this.comprehensiveScore.isApproval = false;
      this.comprehensiveScoreService.complete(this.comprehensiveScore.id, this.comprehensiveScore).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('修改失败，请重试'),
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: ComprehensiveScoreDTO, operation: OperationType): void {
    this.loading = false;
    this.handleCancel();
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('操作成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }

  /**
   * 上传思想分附件
   */
  uploadAttach(fileType: string, files?: SystemFileDTO[]) {
    this.fileType = fileType;
    this.attachFiles = files;
    this.attachSmallComponent.isVisible = true;
    this.isReview = this.isReport === true ? false : this.isPreView;
    this.isShow = this.isReport === true ? true : !this.isPreView;
  }

  /**
   * 将附件弹射回detail
   */
  resultChange(files: SystemFileDTO[]) {
    if (this.fileType === '思想分加分材料') {
      this.comprehensiveScore.ideologicalPoint.files = files;
      this.comprehensiveScore.ideologicalPoint.fileIds = [];
      this.comprehensiveScore.ideologicalPoint.files.forEach(file => {
        this.comprehensiveScore.ideologicalPoint.fileIds.push(file.id);
      });
    }
    if (this.fileType === '文体分加分材料') {
      this.comprehensiveScore.stylisticPoint.files = files;
      this.comprehensiveScore.stylisticPoint.fileIds = [];
      this.comprehensiveScore.stylisticPoint.files.forEach(file => {
        this.comprehensiveScore.stylisticPoint.fileIds.push(file.id);
      });
    }
    if (this.fileType === '学业分加分材料') {
      this.comprehensiveScore.academicPoint.files = files;
      this.comprehensiveScore.academicPoint.fileIds = [];
      this.comprehensiveScore.academicPoint.files.forEach(file => {
        this.comprehensiveScore.academicPoint.fileIds.push(file.id);
      });
    }
  }

  ngOnInit() {}
}
